package com.zcgame.floatview.testdemo.overscroll

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.widget.LinearLayout
import android.widget.OverScroller
import kotlin.math.abs

/**
 *@author:huangLJ
 *@date:2021/7/5 17:49
 */
class CustomView constructor(context: Context,
                             attributeSet: AttributeSet?,
                             val desf:Int = 0):LinearLayout(context,attributeSet,desf) {
    private val scroller = OverScroller(getContext())
    private val configuration = ViewConfiguration.get(context)
    //系统默认滑动的最小值，超过这个值系统就默认滑动
    private val touchSlop = configuration.scaledTouchSlop
    //最小滑动速度
    private val minFlingSpeed = configuration.scaledMinimumFlingVelocity
    //最大滑动速度
    private val maxFlingSpeed = configuration.scaledMaximumFlingVelocity
    //不知道是啥，可能是滑动回弹吧
    private val overFlingDistance = configuration.scaledOverflingDistance
    //滑动回弹
    private val overScrollDistance = configuration.scaledOverscrollDistance;

    private var isFinishScroll:Boolean = true

    init{
        overScrollMode = View.OVER_SCROLL_ALWAYS
        //需要绘制，要设置成false
        setWillNotDraw(false)
    }

    override fun computeScroll() {
        if (scroller.computeScrollOffset()) {
            scrollTo(0,scroller.currY)
        }
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        var lastY = 0f
        when (ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                initVelocityTrackerIfNotExist()
                lastY = y
                isFinishScroll = scroller.isFinished
            }
            MotionEvent.ACTION_MOVE -> {
                val yDi = abs(y - lastY)
                if(yDi > lastY){//滚动的距离是不是滑动
                    isFinishScroll=true
                }
            }
            MotionEvent.ACTION_UP -> {

            }
            else -> {
                return super.onInterceptTouchEvent(ev)
            }
        }
        return super.onInterceptTouchEvent(ev)
    }

    private fun initVelocityTrackerIfNotExist() {
        VelocityTracker.obtain()
    }
}